import { useSocketStore } from '~/store/useSocket'
import { useUserStore } from '~/store/useUser'

export default defineNuxtRouteMiddleware((to, from) => {
    // 只在客户端执行
    if (!process.client) return

    const socketStore = useSocketStore()
    const userStore = useUserStore()
    const token = userStore.getToken

    // 如果有 token 且未连接，则建立连接
    if (token && !socketStore.isConnected) {
        socketStore.initSocket()
    }
    // 如果没有 token 或切换到登录页面，则断开连接
    if (!token) {
        socketStore.socket?.disconnect()
    }
})